package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private IApUserSearchService userSearchService;


    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        // 判断
        if(dto==null|| StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        PageRequest pageRequest = PageRequest.of( dto.getPage().intValue() - 1, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(queryBuilder, pageRequest);

        // 异步保存用户的搜索记录
        userSearchService.saveSearchRecord(dto.getSearchWords(), UserThreadLocalUtil.get().getUserId(), dto.getEquipmentId());

        // 返回结果集
        return ResponseResult.okResult(searchPage.getContent());
    }
}
